/**
 * @file 0502_array_deleter.cpp
 * @author Kun (kun_g@msn.com)
 * @brief 智能指针的deleter行为
 * @version 0.1
 * @date 2024-06-09
 *
 * @copyright Copyright (c) 2024
 *
 */
#include <cstdio>
#include <fstream>
#include <iostream>
#include <memory>
#include <string>
#include <unistd.h>

using namespace std;

class FileDeleter {
private:
  std::string filename;

public:
  FileDeleter(const std::string &fn) : filename(fn) {}

  /**
   * @brief () 运算符重载
   *
   * @param fp 指向 std::ofstream 的指针
   */
  void operator()(std::ofstream *fp) {
    fp->close();
    std::remove(filename.c_str());
    cout << "File " << filename << " deleted." << endl;
  }
};

int main() {
  /**
   * @brief shared_ptr 构造函数的第二个参数为 deleter 类型
   */
  std::shared_ptr<std::ofstream> fp(new std::ofstream("tmpfile.txt"),
                                    FileDeleter("tmpfile.txt"));
  /**
   * @brief 写入临时文件内容
   */
  *fp << "this is a temporary file which will be deleted in 10 seconds."
      << endl;
  sleep(10);
  return 0;
}